package com.jams.goodox.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.login.CourseSearchActivity;
import com.jams.goodox.activity.qa.ClassLearningActivity;
import com.jams.goodox.activity.qa.entity.CourseData;
import com.jams.goodox.adapter.lfadapter.ClassRoomAdapter;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @author HP
 * 课堂
 */
public class ClassRoomFragment extends BaseFragment implements OnItemClickListener,
        LFRecyclerView.LFRecyclerViewListener {


    public static final String TAG = ClassRoomFragment.class.getSimpleName();

    private View rootView;
    LayoutInflater inflater;

    @Bind(R.id.recyclerView)
    LFRecyclerView recyclerView;

    @Bind(R.id.search_btn)
    TextView search_btn;
    Intent intent;

    private List<CourseData> courseDataList = new ArrayList<>();
    private ClassRoomAdapter pAdapter;

    private boolean status = false;//判断加载成功还是失败

    private boolean isRefresh = true;
    private int pageNum = 1;

    Handler handler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            if(msg.what == 1){
                if (isRefresh){
                    recyclerView.stopRefresh(status);
                    pAdapter.notifyDataSetChanged();
                }else {
                    recyclerView.stopLoadMore();
                    pAdapter.notifyDataSetChanged();
                }
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.classroom_fragment, container, false);
            // 初始化页面
            ButterKnife.bind(this, rootView);
        }
        this.inflater = inflater;
        ButterKnife.bind(this, rootView);
        initRecycleView();
        getCourseData();

        return rootView;
    }

    /**
     * 初始化新闻列表页
     */
    private void initRecycleView() {

        search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getActivity(),CourseSearchActivity.class);
                startActivity(intent);
            }
        });
        //recyclerView.addItemDecoration(new MyItemDecoration(DensityUtil.dp2px(getContext(),20)));
        pAdapter = new ClassRoomAdapter(getContext(), courseDataList);
        /*pAdapter.setOnItemClickListener(new ClassRoomAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, ClassRoomAdapter.TViewHolder holder, int position) {

                Log.d(TAG,"position = " + position);

            }
        });*/

//        View linearLayout = inflater.inflate( R.layout.item_header_stick,null);
//        TextView textView = (TextView) linearLayout.findViewById(R.id.tx_city);
//        textView.setText("今日已更新");
        TextView textView = new TextView(getContext());
        textView.setText("今日已更新");
        textView.setPadding(DensityUtil.dp2px(getContext(),5),
                DensityUtil.dp2px(getContext(),5),
                DensityUtil.dp2px(getContext(),5),
                DensityUtil.dp2px(getContext(),5));
        textView.setGravity(Gravity.CENTER);
        recyclerView.setHeaderView(textView);

        recyclerView.setFootText("---我是有底线的---");

        recyclerView.setLoadMore(true);
        recyclerView.setRefresh(true);
        recyclerView.setNoDateShow();
        recyclerView.setAutoLoadMore(false);
        recyclerView.setOnItemClickListener(this);
        recyclerView.setLFRecyclerViewListener(this);
        //recyclerView.setScrollChangeListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.setAdapter(pAdapter);
    }

    private void getCourseData() {
        clearMap();
        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).
                courseIndex(ProtocolManagers.getRequestMap("{" + "\"pageNum\":" + pageNum + ",\"pageSize\":10" + "}"));
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    //data = "[{\"memberId\":13,\"courseId\":97,\"title\":\"如何提高孩子的阅读能力\",\"price\":0.0,\"radioLink\":\"http://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/1525752181839.mp3\",\"nickName\":\"好氧老师\",\"imgPath\":\"http://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/9280E4F399B645D49F4A677A000EB924.png\",\"descr\":\"如何提高孩子的阅读能力，让孩子掌握更好的阅读方式及获取信息的能力\",\"translateState\":2},{\"memberId\":13,\"courseId\":100,\"title\":\"如何与孩子进行有效沟通\",\"price\":0.0,\"radioLink\":\"https://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/1525754731321.mp3\",\"nickName\":\"好氧老师\",\"imgPath\":\"http://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/9280E4F399B645D49F4A677A000EB924.png\",\"descr\":\"有效的与孩子沟通，会使问题变得清晰而简单\",\"translateState\":1},{\"memberId\":13,\"courseId\":101,\"title\":\"孩子的认知能力\",\"price\":0.0,\"radioLink\":\"https://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/1525755420403.mp3\",\"nickName\":\"好氧老师\",\"imgPath\":\"http://hy-pic.oss-cn-shenzhen.aliyuncs.com/file/9280E4F399B645D49F4A677A000EB924.png\",\"descr\":\"快速提高孩子的认知能力\",\"translateState\":1}]";

                    JSONObject jsonObject = new JSONObject(data);
                    if(200 == jsonObject.getInt("code")){
                        status = true;
                        JSONArray jsonArray = new JSONArray(jsonObject.getString("responseData"));

                        if(isRefresh){
                            courseDataList.clear();
                        }
                        for (int i = 0; i < jsonArray.length(); i ++){
                            JSONObject object = jsonArray.getJSONObject(i);
                            CourseData courseData = new CourseData();
                            courseData.setCourseId(object.getInt("courseId"));
                            courseData.setImgPath(object.getString("imgPath"));
                            courseData.setNickName(object.getString("nickName"));
                            courseData.setPrice(object.getDouble("price"));
                            courseData.setTitle(object.getString("title"));
                            courseData.setRadioLink(object.getString("radioLink"));
                            courseData.setContent(object.getString("descr"));

                            courseDataList.add(courseData);
                            Log.d(TAG, "courseData = " + courseData.toString());
                        }

                        pAdapter.notifyDataSetChanged();

                    }else {
                        status = false;
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                status = false;
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

        handler.sendEmptyMessageDelayed(1,300);
    }


    @Override
    public void onClick(int position) {
        Log.d(TAG,"-----onClick--------" + position);
        if(SePref.isLogin()){
            intent = new Intent(getActivity(),ClassLearningActivity.class);
            intent.putExtra("courseId",courseDataList.get(position).getCourseId());
            intent.putExtra("imagePath",courseDataList.get(position).getImgPath());
            intent.putExtra("nickName",courseDataList.get(position).getNickName());
            if(courseDataList.get(position).getPrice() <= 0){
                intent.putExtra("canShare",true);
            }else {
                intent.putExtra("canShare",false);
            }
            startActivity(intent);
        }else {
            if(courseDataList.get(position).getPrice() <= 0){
                intent = new Intent(getActivity(),ClassLearningActivity.class);
                intent.putExtra("courseId",courseDataList.get(position).getCourseId());
                intent.putExtra("imagePath",courseDataList.get(position).getImgPath());
                intent.putExtra("nickName",courseDataList.get(position).getNickName());
                if(courseDataList.get(position).getPrice() <= 0){
                    intent.putExtra("canShare",true);
                }else {
                    intent.putExtra("canShare",false);
                }
                startActivity(intent);
            }else {
                ToastUtil.show("请登录后查看");
            }
//            intent = new Intent(getActivity(),LoginActivity.class);
//            startActivity(intent);
        }

    }

    @Override
    public void onLongClick(int po) {

    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        pageNum = 1;
        getCourseData();
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        isRefresh = false;
        getCourseData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
